import * as VueRouter from "vue-router";
import _ from "lodash";
import {
  AppRouteRecordRaw,
  RouterExtraOptions,
  RouterOptions,
} from "./app-router-type.ts";
import {
  defaultRouterOptions,
  defaultRouterExtraOptions,
} from "./app-router-default-config.js";
import handleAfterNavigation from "./handle-after-navigation.ts";
import handleBeforeNavigation from "./handle-before-navigation.ts";
import AppRouterUtil from "./app-router-util.ts";

/**
 * 创建Router的API。
 *
 * 与VueRouter保持一致，额外增加extraOptions选项
 * */
export const createRouter = (
  options: RouterOptions,
  extraOptions?: RouterExtraOptions,
): VueRouter.Router => {
  const routerOptions = _.defaultsDeep(options, defaultRouterOptions);
  // 转换为VueRoutes
  routerOptions.routes = AppRouterUtil.convertToVueRoutes(routerOptions.routes);

  // 创建VueRouter
  const router = VueRouter.createRouter(routerOptions);

  // 处理AppRouter自定义选项
  const routerExtraOptions = extraOptions
    ? _.defaultsDeep(extraOptions, defaultRouterExtraOptions)
    : defaultRouterExtraOptions;

  router.beforeEach((to, from) => {
    return handleBeforeNavigation(to, from, routerExtraOptions);
  });

  router.afterEach((to, from, failure) => {
    return handleAfterNavigation(to, from, routerExtraOptions, failure);
  });
  return router;
};

/** 定义route的函数，具有类型提示 */
export function defineRoute(route: AppRouteRecordRaw) {
  return route;
}
